<template>
  <div v-if="visible" class="fullscreen-cropper-wrap" @click="closeFullscreen">
    <div
        class="cropper-container"
        :style="{
        width: `${cropperWidth}px`,
        height: `${cropperHeight}px`
      }"
        @click.stop
    >
      <!-- 修复：使用标准<img>标签 -->
      <VueCropper
          ref="cropperRef"
          :img="option.img"
          :output-size="option.outputSize"
          :output-type="option.outputType"
          :can-scale="option.canScale"
          :auto-crop="option.autoCrop"
          :auto-crop-width="option.autoCropWidth"
          :auto-crop-height="option.autoCropHeight"
          :can-move-box="option.canMoveBox"
          :can-move="option.canMove"
          :center-box="option.centerBox"
          :info="option.info"
          :fixed-box="option.fixedBox"
          :fixed="option.fixed"
          :fixed-number="option.fixedNumber"
      />
    </div>
  </div>
<!--  <el-button @click="showPicture">显示裁剪器</el-button>-->
</template>

<script lang="ts" setup>
import { reactive, ref, watch} from 'vue';
import {uploadFile2} from "@/api/modules/system/upload";
import {createDetailModePictureApi} from "@/api/modules/detailModel/detailModePicture";
import type {DetailModePictureForm} from "@/api/types/detailmodel/detailModePicture";
import {ElMessage} from "element-plus";

const visible = ref(false);
const imageWidth = ref(500);
const imageHeight = ref(500);
const cropperWidth = ref(0);
const cropperHeight = ref(0);

let cropperRef = ref();

let props = defineProps({
  masterId: Number
})

let emit = defineEmits(['refreshPictureData'])


const showPicture = (srcUrl :any) => {
  console.log('触发了',option.img)
  option.img = srcUrl;
  visible.value = true;

}

//只要方法进来了就会触发，因此不适合用作初始化
// onMounted(() => {
//   if (option.img) {
//     test(option.img);
//   }
// });

let changeImage =(src: string) => {

  //设置宽高
  const img = new Image();
  img.src = option.img;
  console.log('检测到变更',option.img)

  img.onload = () => {
    imageWidth.value = img.width;
    imageHeight.value = img.height;

    // 设置容器宽高（限制最大尺寸）
    const maxWidth = window.innerWidth * 0.9;
    const maxHeight = window.innerHeight * 0.9;
    cropperWidth.value = imageWidth.value;
    cropperHeight.value = imageHeight.value;

    if (cropperWidth.value > maxWidth) {
      cropperHeight.value = (cropperHeight.value * maxWidth) / cropperWidth.value;
      cropperWidth.value = maxWidth;
    }
    if (cropperHeight.value > maxHeight) {
      cropperWidth.value = (cropperWidth.value * maxHeight) / cropperHeight.value;
      cropperHeight.value = maxHeight;
    }
  };

}


const option = reactive({
  img: 'default',
  outputSize: 1,
  outputType: 'jpeg',
  canScale: true,
  autoCrop: true,
  autoCropWidth: 370,
  autoCropHeight: 565,
  canMoveBox: true,  // 禁用移动裁剪框
  canMove: false,     // 禁用裁剪框缩放
  centerBox: true,    // 裁剪框居中
  info: true,
  fixedBox: true,     // 启用固定裁剪框
  fixed: false,
  fixedNumber: [1, 1],
});


watch(visible,(newValue,oldValue)=>{
  if (newValue  == false){
    console.log("触发了窗口关闭")
    //不明原因爆红
    cropperRef.value.getCropChecked((canvas :any)=>{
      canvas.toBlob((blob:any )=> {
        const file = new File([blob], "cropped-image.png", { type: "image/png" });
        try {
          const formData = new FormData();
          formData.append('avatar', file);  // 假设 imageData 是一个 Base64 字符串或 Blob 数据
          uploadFile2({uploadSelf: file}).then(res =>{
            let url = res?.data
            let save : DetailModePictureForm={
              belongId: props.masterId,
              pictureId:url,
              isAvatar:"1",
            }
            createDetailModePictureApi(save).then(res =>{
              ElMessage.success('保存封面成功')
              emit('refreshPictureData')
            })
          })

        } catch (error) {
          console.error('上传头像失败:', error);
        }
      });
    })
  }
})

//稳定的都是用方法
watch(() => option.img, (newValue) => {
  if (newValue) {
    changeImage(newValue);
  }
});



const closeFullscreen = () => {
  visible.value = false;
};

defineExpose({showPicture})
</script>

<style scoped>


.fullscreen-cropper-wrap {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.85);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  cursor: zoom-out;
}

.cropper-container {
  max-width: 90vw;
  max-height: 90vh;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
}

/* 让图片适应容器（保持比例） */
.cropper-container img {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 保持图片比例，不拉伸 */
}
</style>
